<template>
	<view class="flex item-center search-box">
		<image src="@/static/svg/publicSvg/icon-search.svg" mode="heightFix" class="icon-search"></image>
		<input type="text" placeholder="请输入商品名称" class="search-text" v-model="params.goodsName">
	</view>
	<view class="menu-list flex item-center justify-between">
		<view class="menu-item" v-for="item in menuList" :key="item.id" @click="changeMenu(item)"
			:class="{'active':item.id == params.goodsState}">
			{{item.name}}({{item.num}})
			<view class="sel-line" v-if="item.id == params.goodsState"></view>
		</view>
	</view>
	<view class="sel-asc flex justify-between">
		<view class="flex item-center">
			<view class="asc-item flex item-center" @click="changeOrderBy(1)" v-if="params.goodsState == 3">
				<text class="asc-text" :class="{'active':params.goodsSort == 1}">最新</text>
				<view class="flex flex-col">
					<image class="icon-up"
						:src="params.orderBy == 1 && params.goodsSort == 1?'../../static/svg/goods/sel-vector.svg':'../../static/svg/goods/vector.svg'"
						mode=""></image>
					<image class="icon-down"
						:src="params.orderBy == 2 && params.goodsSort == 1?'../../static/svg/goods/sel-vector.svg':'../../static/svg/goods/vector.svg'"
						mode=""></image>
				</view>
			</view>
			<view class="asc-item flex item-center" @click="changeOrderBy(2)" v-if="params.goodsState == 3">
				<text class="asc-text" :class="{'active':params.goodsSort == 2}">销量</text>
				<view class="flex flex-col">
					<image class="icon-up"
						:src="params.orderBy == 1 && params.goodsSort == 2?'../../static/svg/goods/sel-vector.svg':'../../static/svg/goods/vector.svg'"
						mode=""></image>
					<image class="icon-down"
						:src="params.orderBy == 2 && params.goodsSort == 2?'../../static/svg/goods/sel-vector.svg':'../../static/svg/goods/vector.svg'"
						mode=""></image>
				</view>
			</view>
			<view class="asc-item flex item-center" @click="changeOrderBy(3)" v-if="params.goodsState == 2">
				<text class="asc-text" :class="{'active':params.goodsSort == 3}">最新下架</text>
				<view class="flex flex-col">
					<image class="icon-up"
						:src="params.orderBy == 1 && params.goodsSort == 3?'../../static/svg/goods/sel-vector.svg':'../../static/svg/goods/vector.svg'"
						mode=""></image>
					<image class="icon-down"
						:src="params.orderBy == 2 && params.goodsSort == 3?'../../static/svg/goods/sel-vector.svg':'../../static/svg/goods/vector.svg'"
						mode=""></image>
				</view>
			</view>
		</view>
		<view class="batch-item flex item-center" @click="activeList()" :style="{color:batch?'#FA4543':''}">
			<image class="sel-list" src="@/center/static/svg/goods/sel-list.svg" mode="" v-if="!batch"></image>
			<image class="sel-list" src="@/center/static/svg/goods/sel-list-active.svg" mode="" v-else></image>
			批量
		</view>
	</view>
	<scroll-view scroll-y="true" :style="{'height':scrollHeight}" @scrolltolower='scrolltolower'
		refresher-enabled='true' :refresher-triggered="triggered" @refresherrestore="onRestore"
		@refresherrefresh="onRefresh">
		<view class=" flex item-center" :class="{'goods-batch-w':batch}" v-for="goods in list" :key="goods.id">
			<view v-if="batch">
				<image src="@/static/svg/publicSvg/radio-checked.svg" mode="" class="radio-default"
					@click="batchGoodsByItem(goods)" v-if="selOffList.includes(goods.id)"></image>
				<image src="@/static/svg/publicSvg/radio-default.svg" mode="" class="radio-default"
					@click="batchGoodsByItem(goods)" v-else></image>
			</view>
			<view class="goods-item">
				<view class="flex justify-between">
					<view class="img-box">
						<image :src="goods.goodsImgs" mode="" class="goods-img"></image>
						<view class="pft-box" v-if="goods.verifyType">
							<image src="@/center/static/svg/goods/pft-ticket.svg" mode="" class="pft-ticket"></image>
							<text class="pft-text">票付通</text>
						</view>
					</view>
					<view class="goods-dec flex flex-col justify-between">
						<view class="goods-name">{{goods.goodsName||'暂无标题'}}</view>
						<view class="goods-count flex item-center justify-between" v-if="params.goodsState==1">
							<view>
								编辑时间：{{goods.updateTime||goods.createTime}}
							</view>
						</view>
						<view class="goods-count flex item-center justify-between" v-else>
							<view>
								<text>30日销量 {{goods.saleCount}}</text>
								| <text>可用库存 {{goods.remainStock}}</text>
							</view>
							<text class="goods-price">¥{{goods.goodsPrice}}</text>
						</view>
					</view>
				</view>
				<view class="fs-12 pt-2 merchant-name">
					<text>所属商户：{{goods.merchantShortName}}</text>
				</view>
				<view class="btn-box flex flex-r-r">
					<view class="opt-btn" v-if="params.goodsState == 2 || params.goodsState == 1"
						@click="operItem(goods,'delete')">删除</view>
					<view class="opt-btn" v-if="params.goodsState == 2" @click="operItem(goods,'downOn')">上架</view>
					<view class="opt-btn" v-if="params.goodsState == 3" @click="operItem(goods,'downOff')">下架</view>
					<view class="opt-btn" v-if="params.goodsState == 2" @click="operItem(goods,'stock')">改库存</view>
					<view class="opt-btn" v-if="params.goodsState == 2" @click="operItem(goods,'goodsPrice')">改价</view>
					<view class="opt-btn blue-btn" @click="release(goods)" v-if="params.goodsState != 3">编辑</view>
				</view>
			</view>
		</view>
	</scroll-view>
	<view>
		<view class="release-btn" @click="release" v-if="!batch">发布商品</view>
		<view v-else class="batch-btn-box flex item-center justify-between">
			<view class="flex item-center" @click="ChangeSelOffList()">
				<image src="@/static/svg/publicSvg/radio-checked.svg" mode="" class="radio-default"
					v-if="list.length == selOffList.length"></image>
				<image src="@/static/svg/publicSvg/radio-default.svg" mode="" class="radio-default" v-else></image>
				<text>已选 <text class="sel-num">{{selOffList.length}}</text>/{{list.length}}</text>
			</view>
			<view class="release-btn" @click="operItem({},'batch')" v-if="params.goodsState == 3">批量下架</view>
			<view class="release-btn" @click="operItem({},'batchUp')" v-if="params.goodsState == 2">批量上架</view>
			<view class="release-btn" @click="operItem({},'batchDel')" v-if="params.goodsState == 1">批量删除</view>
		</view>
	</view>

	<!-- 普通弹窗 -->
	<uni-popup ref="popup" type="bottom">
		<view v-if="popType == 'stock'||popType == 'goodsPrice'" class="pop-box pop-stock flex flex-col item-center">
			<view class="pop-title">{{popType == 'stock'?'改库存':'改价'}}</view>
			<view v-if="popType == 'stock'">
				<view class="flex item-center stock-box" style="margin-bottom: 6rpx;">
					<text class="stock-title">总库存</text>
					<input class="stock-num" type="number" placeholder="请输入库存" :maxlength="8"
						v-model="popGoods.totalStock">
				</view>
				<view class="stock-tip">*不可低于当前冻结库存<text class="tip-num">{{popGoods.freezeStock}}</text></view>
			</view>
			<view v-if="popType == 'goodsPrice'" class="flex item-center stock-box">
				<text class="stock-title">商品售价</text>
				<input class="stock-num" type="digit" placeholder="请输入商品售价" v-model="popGoods.goodsPrice">
			</view>
			<view class="pop-btn-box flex justify-between">
				<view class="pop-btn" @click="callBack">取消</view>
				<view class="pop-btn pop-red" @click="sendSubmit(1)">确定</view>
			</view>
		</view>
		<view class="pop-box flex flex-col item-center" v-else>
			<view class="pop-alert">!</view>
			<view class="pop-title" v-if="popType == 'delete'">{{params.goodsState == 2?'确定要删除该商品？':'确定删除该草稿？'}}</view>
			<view class="pop-title" v-if="popType == 'downOn'">确定上架该商品？</view>
			<view class="pop-title" v-if="popType == 'batchUp'">确定批量上架选中的商品？</view>
			<view class="pop-title" v-if="popType == 'downOff'">确定下架该商品？</view>
			<view class="pop-title" v-if="popType == 'batch'">确定批量下架这些商品？</view>
			<view class="pop-title" v-if="popType == 'batchDel'">确定批量删除这些商品？</view>
			<view class="pop-btn-box flex justify-between">
				<view class="pop-btn" @click="callBack">取消</view>
				<view class="pop-btn pop-red" @click="sendSubmit(1)">确定</view>
			</view>
		</view>
	</uni-popup>
</template>
<!-- 自营 -->
<script setup name="BusinessMerchant">
	import {
		ref,
		watch,
		onMounted,
		reactive,
		computed
	} from 'vue'
	import {
		businessMerchantGoodsPage,
		batchDeleteBusinessMerchantGoods,
		batchDownOnBusinessMerchantGoods,
		downOffBusinessMerchantGoods,
		getBusinessMerchantGoodsCount,
		updateBusinessMerchantGoodsStock,
		updateBusinessMerchantGoodsPrice
	} from '@/center/api/goods.js'
	import {
		mathHeight
	} from '@/utils/index.js'
	import {
		judegDit
	} from '@/utils/index.js'
	import {
		useUserStore
	} from '@/stores/modules/user.js'

	const userStore = useUserStore()

	const batch = ref(false) //批量
	const selOffList = ref([])
	const popup = ref()
	let menuList = reactive([{
			name: '在售商品',
			num: 0,
			id: 3
		},
		{
			name: '待发售',
			num: 0,
			id: 2
		},
		{
			name: '草稿箱',
			num: 0,
			id: 1
		}
	])
	const params = reactive({
		goodsName: '',
		goodsSort: '',
		goodsState: 3,
		orderBy: 2,
		pageNum: 1,
		pageSize: 15,
		goodsPageDto: ''
	})
	const triggered = ref(false)
	let list = ref([])
	let total = ref(0)
	let refreshFlag = ref(false)
	// 获取各标签数量
	const getGoodsNum = async () => {
		let result = await getBusinessMerchantGoodsCount()
		if (result && result.length) {
			result.forEach(item => {
				switch (item.goodsState) {
					case 3:
						menuList[0].num = item.num
						break;
					case 2:
						menuList[1].num = item.num
						break;
					case 1:
						menuList[2].num = item.num
						break;
					default:
						break;
				}
			})
		}
	}
	// 获取列表
	const getList = async () => {
		triggered.value = true
		uni.showLoading()
		let result = await businessMerchantGoodsPage({
			...params
		})
		if (result) {
			list.value = params.pageNum == 1 ? result.list : (list.value).concat(result.list)
			total.value = result.total
		}
		uni.hideLoading()
		triggered.value = false
		refreshFlag.value = false
	}
	const reFresh = () => {
		list.value = []
		params.pageNum = 1
		getList()
	}

	const changeMenu = (item) => {
		params.goodsState = item.id
		params.goodsSort = ''
		params.orderBy = 2
		selOffList.value = []
		batch.value = false
		reFresh()
	}
	const changeOrderBy = (i) => {
		if (i != params.goodsSort) {
			params.goodsSort = i
			params.orderBy = 2
		} else {
			if (params.orderBy == 1) {
				params.goodsSort = ''
			}
			params.orderBy = params.orderBy == 2 ? 1 : 2
		}
		reFresh()
	}
	const scrolltolower = () => {
		if (list.value.length >= total.value) {
			return
		}
		params.pageNum = params.pageNum + 1
		getList()
	}
	const onRestore = () => {
		// setTimeout(() =>{
		triggered.value = false; // 需要重置
		// },2000)
		// console.log("onRestore");
	}
	const onRefresh = () => {
		triggered.value = true
		reFresh()
	}

	// 删除
	let popType = ref(null)
	let popGoods = ref(null)
	const operItem = (goods, type) => {
		if (type == 'batch' && !selOffList.value.length) {
			uni.showToast({
				icon: 'none',
				title: `请选择要批量下架的商品`
			})
			return
		}
		if (type == 'batchDel' && !selOffList.value.length) {
			uni.showToast({
				icon: 'none',
				title: `请选择要批量删除的商品`
			})
			return
		}
		if (type == 'batchUp' && !selOffList.value.length) {
			uni.showToast({
				icon: 'none',
				title: `请选择要批量上架的商品`
			})
			return
		}
		// console.log(2222)
		popup.value.open(type == 'stock' || type == 'goodsPrice' ? 'center' : 'bottom')
		popType.value = type
		popGoods.value = JSON.parse(JSON.stringify(goods))
	}
	watch(() => params.goodsName, (val) => {
		reFresh()
	})
	watch(() => refreshFlag.value, (val) => {
		if (val) {
			reFresh()
		}
	})
	const callBack = () => {
		popup.value.close('bottom')
		setTimeout(() => {
			popType.value = null
			popGoods.value = null
		}, 500)


	}
	const sendSubmit = async () => {
		let result = null
		// console.log(popType.value,'popType.value')
		if (popType.value == 'delete') {
			result = await batchDeleteBusinessMerchantGoods({
				ids: [popGoods.value.id]
			})
		} else if (popType.value == 'downOn') {
			// 上架
			result = await batchDownOnBusinessMerchantGoods({
				ids: [popGoods.value.id],
				// merchantId: userInfo.id
			})
		} else if (popType.value == 'downOff') {
			// 下架
			result = await downOffBusinessMerchantGoods({
				ids: [popGoods.value.id],
				// merchantId: userInfo.id
			})
		} else if (popType.value == 'stock') {
			if (popGoods.value.freezeStock > popGoods.value.totalStock) {
				uni.showToast({
					icon: 'none',
					title: `不可低于当前冻结库存${popGoods.value.freezeStock}`
				})
				return
			}
			result = await updateBusinessMerchantGoodsStock({
				"id": popGoods.value.id,
				// "merchantId": userInfo.id,
				"totalStock": popGoods.value.totalStock
			})
		} else if (popType.value == 'goodsPrice') {
			if (!popGoods.value.goodsPrice) {
				uni.showToast({
					icon: 'none',
					title: `请输入商品售价`
				})
				return
			}
			if (!judegDit(popGoods.value.goodsPrice)) {
				uni.showToast({
					icon: 'none',
					title: '商品售价至多只可保留两位小数',
				})
				return
			}
			if (Number(popGoods.value.goodsPrice) > 99999999 || Number(popGoods.value.goodsPrice) < 0) {
				uni.showToast({
					icon: 'none',
					title: '商品售价需在0-99999999元之间',
				})
				return
			}
			if ((Number(popGoods.value.originPrice) < Number(popGoods.value.goodsPrice))) {
				uni.showToast({
					icon: 'none',
					title: `商品售价不可大于划线价格${popGoods.value.originPrice}元`
				})
				return
			}
			result = await updateBusinessMerchantGoodsPrice({
				"id": popGoods.value.id,
				// "merchantId": userInfo.id,
				"goodsPrice": popGoods.value.goodsPrice
			})
		} else if (popType.value == 'batch') {
			result = await downOffBusinessMerchantGoods({
				ids: selOffList.value,
				// merchantId: userInfo.id
			})
		} else if (popType.value == 'batchDel') {
			result = await batchDeleteBusinessMerchantGoods({
				ids: selOffList.value,
				// merchantId: userInfo.id
			})
		} else if (popType.value == 'batchUp') {
			result = await batchDownOnBusinessMerchantGoods({
				ids: selOffList.value,
				// merchantId: userInfo.id
			})
		}
		console.log(result)
		if (result != null) {
			getGoodsNum()
			uni.showToast({
				icon: 'none',
				title: '操作成功'
			})
			reFresh()
			if (popType.value == 'batch' || popType.value == 'batchUp' || popType.value == 'batchDel') {
				selOffList.value = []
				batch.value = false
			}
		} else {
			uni.showToast({
				icon: 'none',
				title: '操作失败，请稍后再试'
			})
		}
		callBack()
	}
	const release = (goods) => {
		let params = `${goods && goods.id?'?id='+goods.id:''}`
		uni.navigateTo({
			url: `/center/pages/goods/releaseBusinessGoodsPage${params}`,
			events: {
				reFreshPage: (data) => {
					getGoodsNum()
					reFresh()
				}
			},
			success: (res) => {
				if (goods && goods.id) {
					res.eventChannel.emit('acceptData', {
						data: goods
					})
				}
			}
		})
	}
	// 批量处理

	const activeList = () => {
		batch.value = !batch.value
		selOffList.value = []
	}
	const batchGoodsByItem = (item) => {
		if (selOffList.value.includes(item.id)) {
			selOffList.value.splice(selOffList.value.indexOf(item.id), 1)
		} else {
			selOffList.value.push(item.id)
		}
	}
	const h = mathHeight(280)
	const scrollHeight = computed(() => (userStore.isOwn ? `calc(${h} - 53px)` : h))
	const ChangeSelOffList = () => {
		if (selOffList.value.length != list.value.length) {
			selOffList.value = (list.value).map(item => {
				return item.id
			})
		} else {
			selOffList.value = []
		}
	}
	onMounted(() => {
		userStore.getUserInfo()
		getGoodsNum()
		getList()
	})
</script>

<style lang="scss" scoped>
	.search-box {
		height: 36px;
		margin: 10px 20px;
		padding: 10px;
		border-radius: 6px;
		background-color: #ffffff;
		min-height: 20px;

		.icon-search {
			height: 20px;
			margin-right: 10px;
		}

		.search-text {
			font-size: 12px;
		}
	}

	.menu-item {
		margin: 10px 20px 4px 20px;
		padding: 10px 0;
		color: #333333;
		position: relative;

		.sel-line {
			position: absolute;
			width: 19px;
			height: 4px;
			border-radius: 4px;
			background: #FA4543;
			bottom: 0;
			left: 0;
			right: 0;
			margin: auto;
		}
	}

	.sel-asc {
		margin: 0 20px;
		padding: 10px 0;
		color: #999999;
		font-size: 14px;
		min-height: 40px;

		.asc-item {
			margin-right: 14px;

			.asc-text {
				margin-right: 4px;

				&.active {
					color: #FA4543;
				}
			}

		}

	}

	.icon-up {
		width: 8px;
		height: 8px;
	}

	.icon-down {
		width: 8px;
		height: 8px;
		transform: rotate(180deg)
	}

	.batch-item {
		color: #999999;
		font-size: 14px;
	}

	.sel-list {
		width: 16px;
		height: 16px;
		margin-right: 6px;
	}

	.goods-item {
		margin: 10px 20px;
		box-sizing: border-box;
		width: calc(100% - 40px);
		padding: 20px;
		background-color: #ffffff;
		border-radius: 8px;

		.img-box {
			position: relative;

			.pft-box {
				position: absolute;
				top: -1px;
				left: -5px;
				font-family: PingFang SC;
				font-size: 8px;
				font-weight: 400;
				line-height: 11px;
				text-align: text;
				width: 32px;
				color: rgba(51, 51, 51, 1);
			}

			.pft-ticket {
				width: 32px;
				height: 19px;
				position: absolute;
				left: 0;
				top: 0;
			}

			.pft-text {
				position: absolute;
				left: 0;
				top: 0;
				width: 100%;
				height: 100%;
				text-align: center;
				line-height: 15px;
				z-index: 2;
			}
		}

		.goods-img {
			width: 60px;
			height: 60px;
			border-radius: 8px;
			background-color: #f5f5f5;
		}

		.goods-dec {
			width: calc(100% - 80px);
		}

		.goods-name {
			font-size: 14px;
			font-weight: 600;
			line-height: 20px;
			letter-spacing: 0px;
			margin-bottom: 10px;
		}

		.goods-count {
			font-size: 12px;
			font-weight: 400;
			line-height: 17px;
			color: #666666;
		}

		.goods-price {
			font-size: 16px;
			font-weight: 600;
			line-height: 22px;
			color: #FA4543;
		}

	}

	.goods-batch-w {
		width: calc(100% + 60px);
	}

	.radio-default {
		height: 24px;
		width: 24px;
		margin: 0 -10px 0 20px;
	}

	.release-btn {
		// width: 343px;
		height: 46px;
		padding: 12px, 20px, 12px, 20px;
		border-radius: 8px;
		// gap: 10px;
		background: #FA4543;
		color: #ffffff;
		margin: 10px 20px;
		text-align: center;
		line-height: 46px;
	}

	.btn-box {
		padding-top: 10px;
		border-top: 1px solid #F5F5F5;
		margin-top: 10px;
		justify-content: flex-end;
	}

	.opt-btn {
		// width: 60px;
		height: 26px;
		padding: 4px 8px;
		border-radius: 8px;
		// line-height: 26px;
		border: 1px solid #999999;
		color: #333333;
		font-size: 12px;
		text-align: center;
		margin-left: 8px;

		&::first-child {
			margin-right: 0;
		}
	}

	.blue-btn {
		color: #00AEFF;
		border: 1px solid #00AEFF;
	}

	.pop-box {
		// padding: 12px;
		margin: 20px;
		background-color: #ffffff;
		border-radius: 12px;

		.pop-alert {
			width: 20px;
			height: 20px;
			border-radius: 50%;
			background: #FCB513;
			text-align: center;
			font-size: 12px;
			color: #ffffff;
			line-height: 20px;
			margin: 20px 0 10px 0;
		}

		.pop-title {
			font-size: 16px;
			font-weight: 600;
			line-height: 24px;
			text-align: center;
			margin-bottom: 10px;
		}

		.pop-text {
			font-size: 12px;
			font-weight: 400;
			line-height: 18px;
			text-align: center;
			color: #898989;
			margin-bottom: 10px;
		}
	}

	.pop-stock {
		width: 320px;
		padding: 20px 0 0 0;

		.stock-tip {
			padding: 10px 0px 0 20px;
			text-align: right;
			font-size: 12px;
			font-weight: 400;
			line-height: 17px;
			width: 100%;
			margin-bottom: 16px;

			.tip-num {
				color: #FA4543;
			}
		}
	}

	.stock-box {
		margin-bottom: 10px;

		.stock-title {
			font-size: 14px;
			font-weight: 600;
			line-height: 20px;
			text-align: right;
			color: #333333;
			width: 80px;
			margin-right: 10px;
		}

		.stock-num {
			background: #F5F5F5;
			height: 44px;
			padding: 12px, 16px, 12px, 16px;
			border-radius: 8px;
			width: calc(100% - 20px);
			text-align: center;
		}
	}

	.pop-btn-box {
		height: 44px;
		font-family: PingFang SC;
		font-size: 16px;
		font-weight: 400;
		line-height: 24px;
		text-align: center;
		border-top: 1px solid #e1e1e1;
		width: 100%;

		.pop-btn {
			height: 44px;
			width: 50%;
			box-sizing: border-box;
			color: rgba(51, 51, 51, .61);
			font-family: PingFang SC;
			font-size: 16px;
			font-weight: 400;
			line-height: 44px;
			letter-spacing: 0em;
			text-align: center;

			&.pop-red {
				color: #FA4543;
				border-left: 1px solid #e1e1e1;
			}
		}
	}

	.batch-btn-box {
		font-size: 12px;

		.radio-default {
			width: 14px;
			height: 14px;
			margin-right: 4px;
		}

		.release-btn {
			width: 229px;
		}

		.sel-num {
			color: #FA4543;
		}
	}

	.merchant-name {
		font-weight: 400;
		line-height: 17px;
		color: #666666;
	}
</style>